Popular Searches
Popular Course Categories
Popular Courses

Understanding JSP Expression Language (EL)

Understanding JSP Expression Language (EL)

JSP Expression Language, JSTL, and Custom Tags

Understanding JSP Expression Language (EL)

Course: Advanced Java Training

Topic: Understanding JSP Expression Language (EL)

Course Link: Advanced Java Training Course

Demo Link: Register for a Course Demo

JustAcademy Website: Visit JustAcademy


1. Introduction to JSP Expression Language (EL)

JSP Expression Language (EL) is a feature of JavaServer Pages that allows developers to access data stored in Java objects, JavaBeans, request attributes, session attributes, application attributes, collections, and other supported data sources directly from a JSP page.

EL simplifies JSP development by reducing the need to write Java expressions or Java code inside the page. It is commonly used to display values prepared by Servlets or other backend components.

For example, the following expression displays a value stored under the request attribute named username:

${username}

When the JSP engine evaluates this expression, it looks for the corresponding attribute and renders its value in the response.

Why Is Expression Language Useful?

  • Provides concise syntax for accessing application data.
  • Reduces Java code embedded in JSP pages.
  • Makes JSP views easier to read and maintain.
  • Supports access to JavaBean properties and collection elements.
  • Provides operators for comparisons, calculations, and logical conditions.
  • Works well with JSTL tags for conditional output and iteration.

2. Learning Objectives

After studying this topic, you should be able to:

  • Explain JSP Expression Language and its purpose.
  • Write EL expressions using the ${...} syntax.
  • Access request, session, and application attributes.
  • Read JavaBean properties and values from arrays, lists, and maps.
  • Use EL operators and implicit objects.
  • Apply EL in JSP pages with Servlet controllers.
  • Identify common EL errors and follow secure coding practices.

3. What Is JSP Expression Language?

JSP Expression Language is a standardized expression syntax used to retrieve and evaluate values in a JSP page. It is especially useful in the presentation layer, where data prepared by the application needs to be displayed to the user.

EL expressions are generally written between ${ and }. The JSP container evaluates the expression and inserts its result into the generated response.

Basic Example

<h2>Welcome, ${username}!</h2>

If the attribute username contains the value Priya, the rendered HTML contains:

<h2>Welcome, Priya!</h2>

The JSP page does not need to call a Java getter explicitly. EL resolves the name and retrieves the relevant value using the rules supported by the JSP container.

4. JSP EL Syntax

The standard immediate-evaluation syntax is:

${expression}

The expression can contain a variable name, property access, collection lookup, an operator, a function, or a combination of supported EL constructs.

Expression Purpose Example
Variable or attribute Retrieves a value by name ${username}
Property access Reads a bean property or map entry ${student.name}
Bracket access Reads a property or collection element ${student["name"]}
Arithmetic Performs numeric calculations ${price * quantity}
Comparison Compares values ${score ge 40}
Logical Combines conditions ${loggedIn and active}
Conditional Selects a result based on a condition ${score ge 40 ? "Pass" : "Fail"}

5. Accessing Attributes with EL

Servlets and other application components can store values in different scopes. EL searches for an unqualified attribute name in a defined scope order.

For a simple expression such as ${username}, the lookup order is generally:

  1. Page scope
  2. Request scope
  3. Session scope
  4. Application scope

The first matching attribute is used. If the same attribute name exists in multiple scopes, use a scope-specific implicit object to avoid ambiguity.

Example: Setting a Request Attribute in a Servlet

import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@WebServlet("/welcome")
public class WelcomeServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response)
            throws ServletException, IOException {

        request.setAttribute("username", "Priya");
        request.getRequestDispatcher("/WEB-INF/views/welcome.jsp")
               .forward(request, response);
    }
}

Example: Displaying the Attribute in JSP

<!DOCTYPE html>
<html>
<head>
    <title>Welcome</title>
</head>
<body>
    <h1>Welcome, ${requestScope.username}!</h1>
</body>
</html>

The Servlet prepares the data, and the JSP uses EL to display it. This separation supports the Model-View-Controller (MVC) pattern.

6. EL Implicit Objects

EL provides predefined objects that allow JSP pages to access common scopes, request parameters, headers, cookies, and context information without declaring those objects manually.

Implicit Object Description Example
pageScope Attributes stored in page scope ${pageScope.message}
requestScope Attributes stored in request scope ${requestScope.message}
sessionScope Attributes stored in session scope ${sessionScope.username}
applicationScope Application-wide ServletContext attributes ${applicationScope.siteName}
param Single request parameter value ${param.email}
paramValues All values for a request parameter ${paramValues.hobby[0]}
header Single request header value ${header["User-Agent"]}
headerValues All values for a request header ${headerValues["Accept"][0]}
cookie Cookie objects accessible by name ${cookie.theme.value}
initParam Servlet context initialization parameters ${initParam.supportEmail}
pageContext Provides access to JSP page context information ${pageContext.request.method}

Other EL objects, such as empty, are operators rather than implicit objects. The distinction is useful when reading EL expressions.

6.1 Using Request Parameters

Suppose a form submits an input field named email to a JSP page. The submitted value can be accessed with:

<p>Submitted email: ${param.email}</p>

For a URL such as /search.jsp?keyword=java, the expression ${param.keyword} resolves to java. Request parameters are user-controlled input and should be validated before being used in business logic.

6.2 Using Session Attributes

<p>Signed-in user: ${sessionScope.username}</p>

This expression reads the attribute named username from the current HTTP session. It does not itself authenticate the user or guarantee that the session is valid for a particular operation.

6.3 Using Application Attributes

<p>Application: ${applicationScope.siteName}</p>

Application-scope attributes can be shared by requests handled by the same web application. Use this scope only for data that is appropriate to share application-wide.

7. Accessing JavaBean Properties

EL can read properties of JavaBean-style objects. For example, ${student.name} accesses the name property of an object stored under the attribute student.

A conventional JavaBean exposes properties through public getter methods. For a property called name, the getter is usually getName().

Student JavaBean

public class Student {
    private String name;
    private int age;

    public Student() {
    }

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

Servlet Controller

Student student = new Student("Aarav", 21);
request.setAttribute("student", student);
request.getRequestDispatcher("/WEB-INF/views/student.jsp")
       .forward(request, response);

JSP View

<h2>Student Details</h2>
<p>Name: ${student.name}</p>
<p>Age: ${student.age}</p>

EL resolves the property through the bean's accessible property mechanism. The JSP page should focus on presentation instead of constructing business objects or performing database queries.

8. Dot Notation and Bracket Notation

EL supports two common ways to access properties and elements.

Dot Notation

${student.name}

Dot notation is convenient when the property name is a valid identifier.

Bracket Notation

${student["name"]}

Bracket notation is useful when the key is dynamic, contains characters that are unsuitable for dot notation, or is stored in a variable.

Map Example

<p>City: ${address["city"]}</p>
<p>Postal code: ${address["postal-code"]}</p>

If address is a Map with the corresponding keys, EL retrieves their associated values. The precise behavior depends on the type of object being accessed and the EL resolution rules.

9. Accessing Arrays, Lists, and Maps

EL can retrieve elements from arrays and list-like collections using index notation. It can also access values stored in maps using keys.

Array Example

<p>First subject: ${subjects[0]}</p>

List Example

<p>Second product: ${products[1]}</p>

Map Example

<p>Order status: ${order.status}</p>
<p>Customer city: ${customer["city"]}</p>

Ensure that the collection exists and the requested index or key is valid. Missing values can result in null-like or empty output depending on the expression and how it is used.

10. Operators in JSP Expression Language

EL includes operators for arithmetic, comparison, logic, conditional evaluation, and empty-value checking.

10.1 Arithmetic Operators

Operator Purpose Example
+ Addition ${10 + 5}
- Subtraction ${10 - 5}
* Multiplication ${10 * 5}
/ or div Division ${10 div 2}
% or mod Remainder ${10 mod 3}

10.2 Comparison Operators

Operator Word Form Purpose
== eq Equal to
!= ne Not equal to
< lt Less than
> gt Greater than
<= le Less than or equal to
>= ge Greater than or equal to

Example:

${score ge 40}

This expression evaluates whether the score is greater than or equal to 40.

10.3 Logical Operators

Operator Alternative Purpose
&& and True when both conditions are true
|| or True when either condition is true
! not Negates a condition

Example:

${loggedIn and active}

10.4 Conditional Operator

The conditional operator chooses between two values based on a condition.

${score ge 40 ? "Pass" : "Fail"}

If the score is at least 40, the expression returns Pass; otherwise, it returns Fail.

10.5 The Empty Operator

The empty operator checks whether a value is null or empty according to EL's rules. It is commonly used with strings, arrays, maps, and collections.

${empty students}

This is useful for checking whether a collection contains data before displaying a list. It is not a substitute for validating business rules on the server.

11. Combining EL with JSTL

JSP Expression Language is frequently used with the JavaServer Pages Standard Tag Library (JSTL). JSTL provides tags for conditions, loops, formatting, and other view-layer tasks. EL supplies the values evaluated by those tags.

For example, in an application configured with a compatible JSTL implementation, the core tag library can be declared as follows:

<%@ taglib prefix="c" uri="jakarta.tags.core" %>

The exact tag-library URI depends on the JSTL version and application environment. Older applications may use the legacy URI http://java.sun.com/jsp/jstl/core.

Conditional Output

<c:if test="${score ge 40}">
    <p>Result: Pass</p>
</c:if>

Displaying a Collection

<c:forEach var="student" items="${students}">
    <p>${student.name} - ${student.age}</p>
</c:forEach>

In this example, the Servlet prepares the students collection, and JSTL iterates over it while EL reads each student's properties.

12. Practical Example: Product Summary Page

This example demonstrates how a Servlet passes product information to a JSP view.

Product JavaBean

public class Product {
    private String name;
    private double price;
    private int quantity;

    public Product(String name, double price, int quantity) {
        this.name = name;
        this.price = price;
        this.quantity = quantity;
    }

    public String getName() {
        return name;
    }

    public double getPrice() {
        return price;
    }

    public int getQuantity() {
        return quantity;
    }
}

Servlet Controller Logic

Product product = new Product("Keyboard", 799.00, 2);
request.setAttribute("product", product);
request.getRequestDispatcher("/WEB-INF/views/product.jsp")
       .forward(request, response);

JSP View

<!DOCTYPE html>
<html>
<head>
    <title>Product Summary</title>
</head>
<body>
    <h1>Product Summary</h1>
    <p>Product: ${product.name}</p>
    <p>Unit price: ${product.price}</p>
    <p>Quantity: ${product.quantity}</p>
    <p>Subtotal: ${product.price * product.quantity}</p>
</body>
</html>

The page displays the product name, unit price, quantity, and calculated subtotal. For real financial applications, perform authoritative monetary calculations using suitable server-side numeric types, such as BigDecimal, rather than relying on floating-point arithmetic in a view.

13. EL Evaluation: Immediate and Deferred Expressions

JSP supports expression forms associated with different evaluation models.

  • Immediate evaluation: ${...} is evaluated when the JSP processes the expression.
  • Deferred evaluation: #{...} is used in technologies and attributes that support deferred evaluation, especially JavaServer Faces value and method expressions.

Do not assume that #{...} behaves exactly like ${...} in every JSP context. Its availability and meaning depend on the technology and the attribute in which it is used.

14. JSP EL and Java Scriptlets: Differences

Feature Expression Language Java Scriptlets
Syntax ${username} <% out.print(username); %>
Readability Concise for view expressions Can make markup difficult to read
Primary use Accessing and evaluating view data Embedding Java statements in JSP
Separation of concerns Encourages presentation-focused pages Can mix application logic and markup
Recommended practice Use with Servlet controllers and JSTL Avoid for new JSP development

For maintainable applications, keep business logic in service classes and controllers, and use EL and JSTL to present prepared data.

15. Common Errors and Troubleshooting

Problem Possible Cause Solution
Expression displays literally EL may be disabled or the page is not being processed as JSP Verify the JSP file location, container configuration, and page directives.
Blank output Attribute does not exist or its value is null Check the attribute name and ensure the controller sets it before forwarding.
Wrong attribute value The same name exists in multiple scopes Use an explicit object such as requestScope or sessionScope.
Bean property unavailable Getter is missing, inaccessible, or named incorrectly Verify the bean property and public getter method.
Collection element missing Incorrect index, key, or collection data Validate the collection and index before rendering.
Comparison behaves unexpectedly Unexpected data types or values Normalize and validate data in the backend and review EL coercion rules.
JSTL tags not recognized Missing library or incorrect tag-library URI Check the JSTL dependency and URI for the version in use.
EL function not found Function library declaration or mapping is incorrect Check the tag library descriptor and function declaration.

16. Security Best Practices

  • Validate input: Treat request parameters and headers as untrusted data.
  • Escape output: EL does not automatically provide context-appropriate HTML, JavaScript, CSS, or URL escaping for every output. Use suitable escaping mechanisms, such as JSTL c:out for ordinary HTML text, and choose protections appropriate to the output context.
  • Keep authorization on the server: Hiding a link or button in a JSP does not protect the underlying endpoint.
  • Avoid sensitive data exposure: Do not display passwords, session tokens, private identifiers, or confidential values in page output.
  • Keep business logic out of JSP: Validate permissions and perform important calculations in trusted backend components.
  • Use explicit scopes when helpful: Scope-specific references make data sources clearer and reduce accidental name collisions.
  • Use HTTPS for sensitive applications: Protect data while it travels between the browser and server.

17. Best Practices for Writing EL Expressions

  • Use descriptive attribute names such as currentUser and productList.
  • Use ${requestScope.user.name} when explicit scope access improves clarity.
  • Prepare data in a Servlet or controller before forwarding to the JSP.
  • Use JavaBeans or suitable view models to expose only the data the page needs.
  • Use JSTL for common loops and conditional rendering instead of Java scriptlets.
  • Keep complex calculations and database operations in backend services.
  • Handle missing values and empty collections intentionally.
  • Test the page with normal, empty, invalid, and unexpected input data.

18. Practical Exercises

  1. Welcome Page: Create a Servlet that sets a request attribute called username. Display it using EL.
  2. Student Profile: Create a JavaBean with name, course, and marks properties. Display these properties in JSP.
  3. Scope Comparison: Store the same attribute name in request and session scopes. Display both values explicitly.
  4. Request Parameters: Create a search form and display its submitted keyword using ${param.keyword}. Validate the input in the backend.
  5. Product Summary: Pass a product object to JSP and display its name, price, and quantity.
  6. Collection Rendering: Pass a list of students to a JSP page and iterate over it using JSTL.
  7. Empty Collection Handling: Use the empty operator to handle a list with no entries.

19. Mini Project: Student Information Display

Objective: Build a small MVC-style application that displays student information using a Servlet, a JavaBean, JSP Expression Language, and JSTL.

Project Requirements

  • Create a Student JavaBean with fields such as ID, name, course, and marks.
  • Create a Servlet that prepares a student object or a list of student objects.
  • Store the data in request scope and forward the request to a JSP view.
  • Use EL to access student properties.
  • Use JSTL to iterate over a list and display the records.
  • Display a helpful message when no student records are available.
  • Validate incoming data and escape output appropriately.

Expected Outcome

The JSP page should display student details without embedding Java business logic in the view. The Servlet manages request flow, the JavaBean represents data, and EL provides concise access to that data.

20. Interview Questions and Answers

Q1. What is JSP Expression Language?

Answer: JSP Expression Language is a syntax for accessing and evaluating data in JSP pages without writing Java expressions for routine view operations.

Q2. What is the syntax of EL?

Answer: The common immediate-evaluation syntax is ${expression}.

Q3. What is the difference between ${username} and ${requestScope.username}?

Answer: The first searches standard scopes in order, while the second explicitly retrieves the request-scope attribute named username.

Q4. What are EL implicit objects?

Answer: They are predefined objects such as requestScope, sessionScope, param, header, and cookie that provide access to common JSP and request data.

Q5. How can EL access a JavaBean property?

Answer: If an attribute named student contains a bean with a readable name property, use ${student.name}.

Q6. What is the purpose of the empty operator?

Answer: It checks whether a value is null or empty according to EL's rules. It is often used to handle empty strings and collections.

Q7. Can EL access request parameters?

Answer: Yes. For example, ${param.username} retrieves a single request parameter named username.

Q8. How is EL different from JSTL?

Answer: EL evaluates expressions and retrieves values, while JSTL supplies tags for tasks such as iteration, conditions, and formatting. They are often used together.

Q9. Does EL automatically escape HTML output?

Answer: No. Use context-appropriate output encoding or escaping. For ordinary HTML text, JSTL's c:out can escape XML-sensitive characters when its default escaping behavior is enabled.

Q10. Why should business logic not be placed in JSP pages?

Answer: Separating business logic from presentation improves maintainability, testing, security, and code reuse. Use Servlets or controllers and service classes to prepare the data.

21. Quick Revision Checklist

  • EL commonly uses the ${...} syntax.
  • Unqualified attributes are searched in page, request, session, and application scope order.
  • Use scope-specific objects to identify the source of a value.
  • Access bean properties with dot notation or bracket notation.
  • Use indexes for arrays and lists and keys for maps.
  • Know arithmetic, comparison, logical, conditional, and empty operations.
  • Use param to read request parameters and validate user input in the backend.
  • Combine EL with JSTL for loops and conditional output.
  • Remember that EL alone does not guarantee context-appropriate output escaping.
  • Keep database access and business logic outside JSP pages.

22. Conclusion

JSP Expression Language is an important feature of Java web development because it provides a clear and compact way to access data in JSP views. By using EL with JavaBeans, request and session attributes, collections, and JSTL, developers can build dynamic pages while keeping presentation separate from application logic.

Practice creating Servlet controllers that prepare data and JSP pages that display it through EL. This approach builds a strong foundation for developing maintainable MVC-based Java web applications.


Further Learning

Explore the Advanced Java Training Course for related topics such as Servlets, JSP, JDBC, Hibernate, and enterprise application development.

To discuss course details or request a demonstration, visit the JustAcademy Course Demo Registration Page.

You can also visit the JustAcademy official website for more learning resources.

Previous Next
whatsapp